package cn.cdzdjd.service.impl;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Service;

import cn.cdzdjd.exception.ErrorCode;
import cn.cdzdjd.exception.RenException;
import cn.cdzdjd.service.BiliBiliService;
import cn.cdzdjd.util.JsoupUtil;
import cn.cdzdjd.util.UrlUtil;
import cn.cdzdjd.util.VendorVideoUtil;
import cn.cdzdjd.vo.VideoInfoVO;
import cn.hutool.core.net.URLDecoder;

@Service
public class BiliBiliServiceImpl implements BiliBiliService {

	@Override
	public VideoInfoVO getVideoInfo(String url) {
		try {
			Document document = JsoupUtil.getDocument(url);
			Element body = document.body();
			String data = body.selectFirst("script[type=application/ld+json]").data();
			JSONObject json = new JSONObject(data);
			String videoTitle = URLDecoder.decode(json.getString("name"), Charset.forName("UTF-8"));
			String poster_url = json.getJSONArray("thumbnailUrl").getString(0);
			String videoUrl = VendorVideoUtil.getVideoUrl(url);
			List<String> videoList = new ArrayList<>();
			videoList.add(UrlUtil.setHttps(videoUrl));
			List<String> posterList = new ArrayList<>();
			posterList.add(UrlUtil.setHttps(poster_url));
			return new VideoInfoVO(videoList, posterList, videoTitle, null);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RenException(ErrorCode.PARSE_ERROR);
		}
	}

}
